package vertx;

import io.vertx.core.AbstractVerticle;
import io.vertx.core.Promise;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.handler.BodyHandler;

/**
 * @author 今何许
 * @date 2021-01-11 14:30
 */
public class BodyVerticle extends AbstractVerticle {
  @Override
  public void start(Promise<Void> startPromise) throws Exception {
    // Create a Router
    Router router = Router.router(vertx);

    //获取body参数，添加这句话
    router.route().handler(BodyHandler.create());

    //form-data格式
    //请求头的content-type：application/x-www-form-urlencoded
    router.route("/form").handler(req -> {
      String id = req.request().getFormAttribute("id");
      String name = req.request().getFormAttribute("name");
      req.response()
        .putHeader("content-type", "text/plain")
        .end(new JsonObject().put("id", id).put("name", name).toString());
    });

    //json格式
    //请求头的content-type：application/json
    router.route("/json").handler(req -> {
      JsonObject body = req.getBodyAsJson();
      req.response()
        .putHeader("content-type", "text/plain")
        .end(body.getValue("id").toString());
    });



    //绑定路由
    vertx.createHttpServer().requestHandler(router).listen(8888, http -> {
      if (http.succeeded()) {
        startPromise.complete();
        System.out.println("HTTP server started on port 8888");
      } else {
        startPromise.fail(http.cause());
      }
    });
  }
}
